package com.example.androidtest.demo3;
import android.util.Log;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * Netty客户端的数据处理器类
 */
public class NettyClientHandler extends SimpleChannelInboundHandler<Object> {

    public NettyClientHandler() {

    }

    @Override
    /**
     * 与服务端连接成功的回调
     *
     * @param ctx
     * @throws Exception
     */
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
//        Log.i("nettyConnect", "channelActive");
    }

    //这里是接受服务端发送过来的消息
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object baseMsg) {
        ByteBuf buf = (ByteBuf) baseMsg;
        decode(buf);
    }


    @Override
    /**
     * 与服务端断开的回调
     *
     * 这里是断线要进行的操作
     * @param ctx
     * @throws Exception
     */
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);

//        Log.i("nettyConnect", "channelInactive");

        NettyClient.getInstance().disconnect("channelInactive");
        Thread.sleep(3 * 1000);

//        Log.i("NettyBeatLog", "重连");
        NettyClient.getInstance().connect(new NettyClient.ConnectedCallback() {
            @Override
            //重新连接成功的回调
            public void onConnected() {
                //重连成功的业务逻辑
            }
        });
    }

    //这里是出现异常的话要进行的操作
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);

        Log.i("nettyConnect", "出现异常了。。。。。。。。。。。。。");
        cause.printStackTrace();
        Log.i("nettyConnect", cause.getMessage());

        NettyClient.getInstance().disconnect("异常重连");
        NettyClient.getInstance().connect(new NettyClient.ConnectedCallback() {
            @Override
            //重新连接成功的回调
            public void onConnected() {
                //重连成功的业务逻辑
            }
        });
    }

    //接收到的服务端发送过来的内容
    public void decode(ByteBuf buf) {
        try {
            byte[] b = new byte[buf.readableBytes()];
            buf.readBytes(b);

            String curMsg = new String(b, "UTF-8").trim();
            Log.i("Log", "curMsg == " + curMsg);

            //数据处理的业务逻辑(根据与后端开发人员约定的规则对数据进行处理)
            //...

        } catch (Exception e) {
//            Log.i("netty exception", e.toString());
        }
    }

}

